package com.hmjk.health.background;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

public class NetService extends Service{
	private static final String TAG = NetService.class.getSimpleName();
	private static final boolean DEBUG = true;
	private static final boolean NET_DEBUG = false;
	public static final String INVOKE_BY_ME = "com.hmjk.net.invoke_by_me";
	public static final String VALIDATE_USER_ACCOUNT = "com.hmjk.net.validate_useraccount";
	//public static final String VALIDATE_PHONE_NUMBER = "com.hmjk.net.validate_phone";
	public static final String GET_IDENTIFY_CODE = "com.hmjk.net.identify_code";
	public static final String SIGN_UP_NEW_ACCOUNT = "com.hmjk.net.sign_up";
	public static final String SIGN_IN_ACCOUNT = "com.hmjk.net.sign_in";
	public static final String SIGN_OUT_ACCOUNT = "com.hmjk.net.sign_out";
	public static final String CHANGE_PASSWORD = "com.hmjk.net.change_pwd";
	public static final String RETRIEVE_PASSWORD = "com.hmjk.net.retrieve_pwd";
	public static final String APPLY_JOIN_FAMILY = "com.hmjk.net.apply_join_fa";
	public static final String ADD_NEW_DEVICE = "com.hmjk.net.add_new_device";
	public static final String ACTIVATE_DEVICE = "com.hmjk.net.activate_device";
	
	public static final String APPLY_INTEREST_DEV = "com.hmjk.net.apply_interest_dev";
	public static final String DOWNLOAD_AD_ACTION = "com.hmjk.net.download_ad";
	
	public static final String GET_DATA_ACTION = "com.hmjk.net.get_data";
	public static final String DOWNLOAD_ACTION = "com.hmjk.net.download";
	public static final String COMMIT_DATA_ACTION = "com.hmjk.net.commit_data";
	
	public static final String GET_FAMILY_DETAIL = "com.hmjk.net.get_family_detail";
	public static final String COMMIT_FAMILY_DETAIL = "com.hmjk.net.commit_family_detail";
	
	public static final String GET_DEV_LOCA_PARAM = "com.hmjk.net.get_loca_param";
	public static final String SET_DEV_LOCA_PARAM = "com.hmjk.net.set_loca_param";	
	public static final String GET_GLYCOSE_HISTORY_DATA = "com.hmjk.net.get_gly_history";
	public static final String GET_BP_HISTORY_DATA = "com.hmjk.net.get_bp_history";
	
	
	/* sub action in GET_DATA_ACTION intent*/ 
	public static final String GET_USER_DATA = "act_get_user_data";
	public static final String CHECK_USER_FACE = "act_check_user_face";
	public static final String GET_FAMILY_LIST = "act_get_family_list";
	public static final String GET_DEVICE_LIST = "act_get_device_list";
	public static final String GET_DEVICE_SUB_LIST = "act_get_device_sub_list";
	public static final String GET_DEVICE_SUB_INFO = "act_get_device_sub_info";
	public static final String CHECK_DEVICE_FACE = "act_check_device_face";
	public static final String GET_FAMILY_MEMBER = "act_get_family_members";
	public static final String CHECK_DEVICE_SETTINGS = "act_get_device_settings";
	public static final String GET_DEVICE_POWER = "act_get_device_power";
	public static final String GET_DEVICE_LOCATION_PAGE = "act_get_device_location_page";
	//public static final String GET_DEVICE_LOCATION_COUNT = "act_get_device_location_count";//api definded but we haddent used it.
	public static final String GET_DEVICE_LOCATION_NEWEST = "act_get_device_location_newest";
	public static final String GET_TODO_LIST = "act_get_todo_list";
	public static final String GET_CARE_REMINDER = "act_get_care_reminder";
	public static final String GET_MEASURE_REMINDER = "act_get_measure_reminder";
	public static final String GET_DRUG_REMINDER = "act_get_drug_reminder";
	public static final String GET_GLYCOSE_SET = "act_get_glycose_set";
	public static final String GET_GLYCOSE_DATA = "act_get_glycose_data";
	public static final String GET_GLYCOSE_DATA_PERIOD = "act_get_glycose_data_period";
	public static final String GET_BP_DATA_PERIOD = "act_get_bp_data_period";
	
	
	
	/* sub action in DOWNLOAD_ACTION intent*/
	public static final String DOWNLOAD_USER_FACE = "act_dl_user_face";
	public static final String DOWNLOAD_DEVICE_FACE = "act_dl_device_face";
	
	/* sub action in COMMIT_DATA_ACTION intent*/
	public static final String COMMIT_USER_DATA = "act_ci_user_data";
	public static final String COMMIT_BUILD_FAMILY = "act_ci_build_family";
	public static final String COMMIT_TODO = "act_ci_todo";
	public static final String COMMIT_USER_FACE = "act_ci_user_face";
	public static final String COMMIT_DEV_FACE = "act_ci_dev_face";
	public static final String COMMIT_DEVICE_NAME = "act_ci_dev_name";
	public static final String COMMIT_DEVICE_ADMIN_ABORT = "act_ci_dev_abort_admin";
	public static final String COMMIT_DEVICE_ADMIN_APPLY = "act_ci_dev_apply_admin";
	public static final String COMMIT_DEVICE_INTEREST_ABORT = "act_ci_dev_abort_interest";
	public static final String COMMIT_ADMIN_FA = "act_ci_admin_fa";
	public static final String COMMIT_ABORT_BY_ADMIN_FA = "act_ci_abort_by_admin_fa";
	public static final String COMMIT_ABORT_BY_MEMBER_FA = "act_ci_abort_by_member_fa";
	public static final String COMMIT_CARE_REMINDER = "act_ci_care_reminder";
	public static final String COMMIT_MEASURE_REMINDER = "act_ci_measure_reminder";
	public static final String COMMIT_DRUG_REMINDER = "act_ci_drug_reminder";
	public static final String COMMIT_DEVICE_MOBILENUMBER = "act_ci_device_mobile";
	public static final String AUTOSET_DEVICE_MOBILENUMBER = "act_auto_ci_device_mobile";
	public static final String COMMIT_GLYCOSE_SET = "act_ci_glycose_set";
	public static final String COMMIT_GLYCOSE_DATA = "act_ci_glycose_data";
	
	private HealthApp mApp;
	private BlockingQueue<HTTPREQ> mReqQueue = new LinkedBlockingQueue<HTTPREQ>();
	private static final int MAX_QUEUE_SIZE = 30;
	private HttpsThread mThread = null;
	
	private void logd(String info){
		if(DEBUG)
			Log.d(TAG, info);
	}
	
	private void loge(String info){
		Log.e(TAG, info);
	}
	
	private void netLogd(String info){
		if(NET_DEBUG)
			Log.d("NET_DEBUG", info);
	}
	
	private void netLogE(String info){
		Log.e("NET_DEBUG", info);
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}   
	  
    @Override  
    public void onCreate() {  
    	logd("onCreate");
        super.onCreate();  
        
        mApp = (HealthApp)getApplication();
        
        logd("onCreate mApp="+mApp);
        
        mThread = new HttpsThread();
        mThread.start();
        
        /*if(mApp.checkNetwork() && mApp.isUserSignIn()){
        	HTTPREQ r = buildALogInReq();
        	offerREQ(r);
        }*/
    }  
   
    private HTTPREQ buildALogInReq(){
    	logd("buildALogInReq");
    	String user = mApp.getUserName();
    	String pwd = mApp.getPassword();
    	
    	try {
			JSONObject j = new JSONObject();
			j.put("stamp", "SIGN_IN_ACCOUNT_AUTO");
			j.put("user", user);
			j.put("password", pwd);
			HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_SIGN_IN,j.toString());
			return req;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return null;
    }
    
    @Override  
    public void onStart(Intent intent, int startId) {  
        logd("onStart");  
        super.onStart(intent, startId);  
    }  
  
    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {  
    	if(intent == null){
    		logd("onStartCommand auto flags="+flags+" startId="+startId);
    	}else{
    		String action = intent.getAction();
    		logd("onStartCommand action="+action+" flags="+flags+" startId="+startId); 
    		if(INVOKE_BY_ME.equals(action)){
    			if(mApp.checkNetwork() && mApp.isUserSignIn() && (false == mApp.isSignIn())){
    	        	HTTPREQ r = buildALogInReq();
    	        	offerREQ(r);
    	        }
    		}else if(VALIDATE_USER_ACCOUNT.equals(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String account = intent.getStringExtra("account");
    			
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("account", account);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_VALIDATE_ACCOUNT,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}  
    		}else if(GET_IDENTIFY_CODE.equalsIgnoreCase(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String phone = intent.getStringExtra("phone");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("phone", phone);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_IDENTIFY_CODE,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}else if(SIGN_UP_NEW_ACCOUNT.equalsIgnoreCase(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String phone = intent.getStringExtra("phone");
    			String user = intent.getStringExtra("user");
    			String pwd = intent.getStringExtra("password");
    			String idcode = intent.getStringExtra("idcode");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("phone", phone);
    				j.put("user", user);
    				j.put("password", pwd);
    				j.put("idcode", idcode);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_SIGN_UP,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}else if(SIGN_IN_ACCOUNT.equalsIgnoreCase(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String user = intent.getStringExtra("user");
    			String pwd = intent.getStringExtra("password");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("user", user);
    				j.put("password", pwd);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_SIGN_IN,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}else if(SIGN_OUT_ACCOUNT.equalsIgnoreCase(action)){
    			String stamp = intent.getStringExtra("stamp");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_SIGN_OUT,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}else if(CHANGE_PASSWORD.equalsIgnoreCase(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String uid = intent.getStringExtra("uid");
    			String oldpwd = intent.getStringExtra("oldpassword");
    			String newpwd = intent.getStringExtra("newpassword");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("uid", uid);
    				j.put("oldpassword", oldpwd);
    				j.put("newpassword", newpwd);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_CHANGE_PASSWORD,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}else if(RETRIEVE_PASSWORD.equalsIgnoreCase(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String phone = intent.getStringExtra("phone");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("phone", phone);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_RETRIEVE_PASSWORD,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}else if(APPLY_JOIN_FAMILY.equalsIgnoreCase(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String uid = intent.getStringExtra("uid");
    			String fid = intent.getStringExtra("fid");
    			String familystatus = intent.getStringExtra("familystatus");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("uid", uid);
    				j.put("fid", fid);
    				j.put("familystatus", familystatus);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_APPLY_JOIN_FA,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}	
    		}else if(GET_FAMILY_DETAIL.equalsIgnoreCase(action)){
				String stamp = intent.getStringExtra("stamp");
    			String uid = intent.getStringExtra("uid");
    			String fid = intent.getStringExtra("fid");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("uid", uid);
    				j.put("fid", fid);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_FA_DETAIL,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
			}else if(COMMIT_FAMILY_DETAIL.equalsIgnoreCase(action)){
				String stamp = intent.getStringExtra("stamp");
    			String uid = intent.getStringExtra("uid");
    			String fid = intent.getStringExtra("fid");
    			String familyname = intent.getStringExtra("familyname");
				String familyaddress = intent.getStringExtra("familyaddress");
				String familyphoneno = intent.getStringExtra("familyphoneno");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("uid", uid);
    				j.put("fid", fid);
    				j.put("familyname", familyname);
    				j.put("familyaddress", familyaddress);
    				j.put("familyphoneno", familyphoneno);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_FA_DETAIL,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
			}else if(GET_DEV_LOCA_PARAM.equalsIgnoreCase(action)){
				String stamp = intent.getStringExtra("stamp");
				String uid = intent.getStringExtra("uid");
				String tid = intent.getStringExtra("tid");
				try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("uid", uid);
    				j.put("tid", tid);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_LOCA_PARAM,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}	
			}else if(ADD_NEW_DEVICE.equalsIgnoreCase(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String uid = intent.getStringExtra("uid");
    			String did = intent.getStringExtra("did");
    			//String fid = intent.getStringExtra("fid");
    			String devicename = intent.getStringExtra("devicename");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("uid", uid);
    				j.put("did", did);
    				//j.put("fid", fid);
    				j.put("devicename", devicename);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_ADD_NEW_DEVICE,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}	
    		}else if(ACTIVATE_DEVICE.equalsIgnoreCase(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String uid = intent.getStringExtra("uid");
    			String tid = intent.getStringExtra("tid");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("uid", uid);
    				j.put("tid", tid);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_ACTIVATE_DEVICE,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}else if(SET_DEV_LOCA_PARAM.equalsIgnoreCase(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String uid = intent.getStringExtra("uid");
    			String tid = intent.getStringExtra("tid");
    			String fence = intent.getStringExtra("fence");
    			String range = intent.getStringExtra("range");
    			String lat = intent.getStringExtra("lat");
    			String lng = intent.getStringExtra("lng");
    			String rate = intent.getStringExtra("rate");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("uid", uid);
    				j.put("tid", tid);
    				j.put("fence", fence);
    				j.put("range", range);
    				j.put("lat", lat);
    				j.put("lng", lng);
    				j.put("rate", rate);
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_SET_LOCA_PARAM,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}else if(APPLY_INTEREST_DEV.equals(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String uid = intent.getStringExtra("uid");
    			String tid = intent.getStringExtra("tid");
    			String interestuid = intent.getStringExtra("interestuid");
    			String did = intent.getStringExtra("did");
    			String devicename = intent.getStringExtra("devicename");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("uid", uid);
    				j.put("tid", tid);
    				j.put("did", did);
    				j.put("interestuid", interestuid);
    				j.put("devicename", devicename);
    				
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_APPLY_INTEREST_DEV,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}else if(DOWNLOAD_AD_ACTION.equalsIgnoreCase(action)){
    			String stamp = intent.getStringExtra("stamp");
    			String uid = intent.getStringExtra("uid");
    			String tidArrayString = intent.getStringExtra("tidarray");
    			try {
    				JSONObject j = new JSONObject();
    				j.put("stamp", stamp);
    				j.put("uid", uid);
    				j.put("tidarray", new JSONArray(tidArrayString));
    				
    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_DOWNLOAD_AD_ACTION,j.toString());
    				if(false == offerREQ(req)){
    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
    					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
    					mApp.dispatchNetResponse(stamp,result,false);
    				}
    			} catch (JSONException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}else if(GET_DATA_ACTION.equalsIgnoreCase(action)){
    			String subact = intent.getStringExtra("sub_act");
    			if(GET_USER_DATA.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
    				String uid = intent.getStringExtra("uid");
	    			try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("uid", uid);
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_USERDATA,j.toString());
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    			}else if(CHECK_USER_FACE.equalsIgnoreCase(subact)){
        			String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String vuid = intent.getStringExtra("vuid");
        			long vstamp = intent.getLongExtra("vstamp", 0);
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("vstamp", vstamp);
        				j.put("vuid", vuid);
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_CHECK_USERFACE,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_FAMILY_LIST.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("uid", uid);
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_FA_LIST,j.toString());
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    			}else if(GET_DEVICE_LIST.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("uid", uid);
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_DEV_LIST,j.toString());
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    			}else if(GET_DEVICE_SUB_LIST.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String tid = intent.getStringExtra("tid");
        			try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("tid", tid);
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_DEV_SUB_LIST,j.toString());
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}       			
    			}else if(GET_DEVICE_SUB_INFO.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String tid = intent.getStringExtra("tid");
        			String subcode = intent.getStringExtra("subcode");
        			String table = intent.getStringExtra("table");
        			try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("tid", tid);
	    				j.put("subcode", subcode);
	    				j.put("table", table);
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_DEV_SUB_INFO,j.toString());
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}       			
    			}else if(CHECK_DEVICE_FACE.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String vtid = intent.getStringExtra("vtid");
        			long lstamp = intent.getLongExtra("vstamp", 0);
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("vstamp", lstamp);
        				j.put("vtid", vtid);
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_CHECK_DEVFACE,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_FAMILY_MEMBER.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String fid = intent.getStringExtra("fid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("fid", fid);
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_FAMEMBERS,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(CHECK_DEVICE_SETTINGS.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String tid = intent.getStringExtra("tid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid", tid);
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_DEVSETTINGS,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_DEVICE_POWER.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String tidarr = intent.getStringExtra("tidarr");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tidarr", new JSONArray(tidarr));
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_DEVPOWER,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_DEVICE_LOCATION_PAGE.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String tid = intent.getStringExtra("tid");
        			long end = intent.getLongExtra("endtime", 0);
        			long start = intent.getLongExtra("starttime", 0);
        			String pageindex = intent.getStringExtra("pageindex");
        			String pagesize = intent.getStringExtra("pagesize");
        			
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid", tid);
        				j.put("starttime",start);
        				j.put("endtime", end);
        				j.put("pageindex", pageindex);
        				j.put("pagesize", pagesize);
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_QUERY_LOCATION_PAGE,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}/*else if(GET_DEVICE_LOCATION_COUNT.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String tid = intent.getStringExtra("tid");
        			String count = intent.getStringExtra("count");
        			
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid", tid);
        				j.put("count",count);
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_QUERY_LOCATION_COUNT,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}*/else if(GET_DEVICE_LOCATION_NEWEST.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String tid = intent.getStringExtra("tid");
        			String maxrecord = intent.getStringExtra("maxrecord");
        			long fromtimetonow = intent.getLongExtra("fromtimetonow", 0);
        			
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid", tid);
        				j.put("maxrecord",maxrecord);
        				j.put("fromtimetonow",fromtimetonow);
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_QUERY_LOCATION_NEWEST,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_TODO_LIST.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_QUERY_TODO,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_CARE_REMINDER.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid",intent.getStringExtra("tid"));
        				j.put("terminaltype", intent.getStringExtra("terminaltype"));
        				j.put("dex", intent.getStringExtra("dex"));
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_CARE_REMINDER,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_MEASURE_REMINDER.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid",intent.getStringExtra("tid"));
        				j.put("terminaltype", intent.getIntExtra("terminaltype", 0));
        				j.put("dex", intent.getIntExtra("dex", 255));
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_MEASURE_REMINDER,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_DRUG_REMINDER.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid",intent.getStringExtra("tid"));
        				j.put("terminaltype", intent.getIntExtra("terminaltype", 0));
        				j.put("dex", intent.getIntExtra("dex", 255));
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_DRUG_REMINDER,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_GLYCOSE_SET.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid",intent.getStringExtra("tid"));
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_GLYCOSE_SET,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_GLYCOSE_DATA.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid",intent.getStringExtra("tid"));
        				j.put("subcode", intent.getStringExtra("subcode"));                 
        				j.put("fromtimetonow", intent.getLongExtra("fromtimetonow", 0));              
        				j.put("pageindex", intent.getStringExtra("pageindex"));	                 
        				j.put("pagesize", intent.getStringExtra("pagesize"));	 
       				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_GLYCOSE_DATA,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_GLYCOSE_DATA_PERIOD.equalsIgnoreCase(subact) || GET_GLYCOSE_HISTORY_DATA.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid",intent.getStringExtra("tid"));
        				j.put("subcode", intent.getStringExtra("subcode"));                 
        				j.put("starttime", intent.getLongExtra("starttime", 0));  
        				j.put("endtime", intent.getLongExtra("endtime", 0));      
        				j.put("pageindex", intent.getStringExtra("pageindex"));	                 
        				j.put("pagesize", intent.getStringExtra("pagesize"));	 
       				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_GLYCOSE_DATA_PERIOD,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(GET_BP_DATA_PERIOD.equalsIgnoreCase(subact) || GET_BP_HISTORY_DATA.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid",intent.getStringExtra("tid"));
        				j.put("subcode", intent.getStringExtra("subcode"));                 
        				j.put("starttime", intent.getLongExtra("starttime", 0));  
        				j.put("endtime", intent.getLongExtra("endtime", 0));      
        				j.put("pageindex", intent.getStringExtra("pageindex"));	                 
        				j.put("pagesize", intent.getStringExtra("pagesize"));	 
       				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_GET_BP_DATA_PERIOD,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}		
    		}else if(COMMIT_DATA_ACTION.equalsIgnoreCase(action)){
    			String subact = intent.getStringExtra("sub_act");
    			if(COMMIT_USER_DATA.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
    				String uid = intent.getStringExtra("uid");
    				String ac = intent.getStringExtra("username");
    				String mobile = intent.getStringExtra("mobileno");
    				String nick = intent.getStringExtra("nickname");
    				String idcard = intent.getStringExtra("useridcardno");
    				String gender = intent.getStringExtra("gender");
    				String addr = intent.getStringExtra("residentialaddress");
    				String edu = intent.getStringExtra("educationid");
    				String city = intent.getStringExtra("cityid");
    				String occu = intent.getStringExtra("occupationid");
    				String pos = intent.getStringExtra("positionid");
    				
	    			try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("uid", uid);
	    				j.put("username", ac);
	    				j.put("mobileno", mobile);
	    				j.put("nickname", nick);
	    				j.put("useridcardno", idcard);
	    				j.put("gender", gender);
	    				j.put("residentialaddress", addr);
	    				j.put("educationid", edu);
	    				j.put("cityid", city);
	    				j.put("occupationid", occu);
	    				j.put("positionid", pos);
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_USERDATA,j.toString());
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    			}else if(COMMIT_BUILD_FAMILY.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
    				String uid = intent.getStringExtra("uid");
    				String name = intent.getStringExtra("familyname");
    				String status = intent.getStringExtra("familystatus");
    				String admin = intent.getStringExtra("admin");
    				try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("uid", uid);
	    				j.put("familyname", name);
	    				j.put("familystatus", status);
	    				j.put("admin", admin);
	    				
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_BUILDFAMILY,j.toString());
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    			}else if(COMMIT_TODO.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
    				String uid = intent.getStringExtra("uid");
    				String rid = intent.getStringExtra("rid");
    				String rembercode = intent.getStringExtra("rembercode");
    				String remberstate = intent.getStringExtra("remberstate");
    				long rembertime = intent.getLongExtra("rembertime", 0);
    				try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("uid", uid);
	    				j.put("rid", rid);
	    				j.put("rembercode", rembercode);
	    				j.put("remberstate", remberstate);
	    				j.put("rembertime", rembertime);
	    				
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_DEAL_TODO,j.toString());
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    			}else if(COMMIT_USER_FACE.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
    				String uid = intent.getStringExtra("uid");
    				String path = intent.getStringExtra("path");
    				
    				try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("uid", uid);
	    				
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_USERFACE,j.toString());
	    				req.setFilePath(path);
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    			}else if(COMMIT_DEV_FACE.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
    				String uid = intent.getStringExtra("uid");
    				String tid = intent.getStringExtra("tid");
    				String path = intent.getStringExtra("path");
    				
    				try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("uid", uid);
	    				j.put("tid", tid);
	    				
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_DEVFACE,j.toString());
	    				req.setFilePath(path);
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    			}else if(COMMIT_DEVICE_NAME.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String tid = intent.getStringExtra("tid");
        			String devicename = intent.getStringExtra("devicename");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid", tid);
        				j.put("devicename", devicename);
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_UPDATE_DEVICE_NAME,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(COMMIT_DEVICE_ADMIN_ABORT.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String tid = intent.getStringExtra("tid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid", tid);
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_DEVICE_ADMIN_ABORT,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(COMMIT_DEVICE_ADMIN_APPLY.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String tid = intent.getStringExtra("tid");
        			String devicename = intent.getStringExtra("devicename");
        			
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid", tid);
        				j.put("devicename", devicename);
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_DEVICE_ADMIN_APPLY,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(COMMIT_DEVICE_INTEREST_ABORT.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String tid = intent.getStringExtra("tid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid", tid);
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_DEVICE_INTEREST_ABORT,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    			}else if(COMMIT_ADMIN_FA.equalsIgnoreCase(subact)){
        			String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String fid = intent.getStringExtra("fid");
        			String adminuid = intent.getStringExtra("adminuid");
        			String oldadminuid = intent.getStringExtra("oldadminuid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("fid", fid);
        				j.put("adminuid", adminuid);
        				j.put("oldadminuid", oldadminuid);
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_ADMIN_FA,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}	
        		}else if(COMMIT_ABORT_BY_ADMIN_FA.equalsIgnoreCase(subact)){
        			String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String fid = intent.getStringExtra("fid");
        			String uidarray = intent.getStringExtra("uidarray");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("fid", fid);
        				j.put("uidarray",  new JSONArray(uidarray));
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_ABORT_BY_ADMIN_FA,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}	
        		}else if(COMMIT_ABORT_BY_MEMBER_FA.equalsIgnoreCase(subact)){
        			String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String fid = intent.getStringExtra("fid");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("fid", fid);
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_ABORT_BY_MEMBER_FA,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
        		}else if(COMMIT_DEVICE_MOBILENUMBER.equalsIgnoreCase(subact) ||
        				AUTOSET_DEVICE_MOBILENUMBER.equalsIgnoreCase(subact)){
        			String stamp = intent.getStringExtra("stamp");
        			String uid = intent.getStringExtra("uid");
        			String tid = intent.getStringExtra("tid");
        			String simno = intent.getStringExtra("simno");
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", uid);
        				j.put("tid", tid);
        				j.put("simno", simno);
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_DEVICE_MOBILENUMBER,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
        		}else if(COMMIT_CARE_REMINDER.equalsIgnoreCase(subact)){
    				String stamp = intent.getStringExtra("stamp");
       			
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", intent.getStringExtra("uid"));
        				j.put("tid", intent.getStringExtra("tid"));
        				j.put("nickname", intent.getStringExtra("sub_account"));
        				j.put("updatetime", intent.getLongExtra("updatetime", 0));
        				j.put("terminaltype", intent.getStringExtra("terminaltype"));
        				String s = intent.getStringExtra("opt");
        				j.put("opt", intent.getStringExtra("opt"));
        				s = intent.getStringExtra("dex");
        				intent.getStringExtra("terminaltype");
        				j.put("dex", intent.getStringExtra("dex"));
        				j.put("remind", intent.getStringExtra("remind"));
        				j.put("remindmsg", intent.getStringExtra("remindmsg"));
        				j.put("remindmode", intent.getStringExtra("remindmode"));
        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_CARE_REMINDER,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
    		  }else if(COMMIT_MEASURE_REMINDER.equalsIgnoreCase(subact)){

  				String stamp = intent.getStringExtra("stamp");
     			
      			try {
      				JSONObject j = new JSONObject();
      				j.put("stamp", stamp);
      				j.put("uid", intent.getStringExtra("uid"));
      				j.put("tid", intent.getStringExtra("tid"));
      				j.put("subcode", intent.getStringExtra("subcode"));
      				j.put("updatetime", intent.getLongExtra("updatetime", 0));
      				j.put("terminaltype", intent.getStringExtra("terminaltype"));
      				j.put("opt", intent.getStringExtra("opt"));
      				j.put("dex", intent.getStringExtra("dex"));
      				j.put("remind", intent.getStringExtra("remind"));
      				j.put("remindmsg", intent.getStringExtra("remindmsg"));
      				j.put("remindmode", intent.getStringExtra("remindmode"));

      				
      				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_MEASURE_REMINDER,j.toString());
      				if(false == offerREQ(req)){
      					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
      					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
      					mApp.dispatchNetResponse(stamp,result,false);
      				}
      			} catch (JSONException e) {
      				// TODO Auto-generated catch block
      				e.printStackTrace();
      			}
      			
    		  }else if(COMMIT_DRUG_REMINDER.equalsIgnoreCase(subact)){

    				String stamp = intent.getStringExtra("stamp");
       			
        			try {
        				JSONObject j = new JSONObject();
        				j.put("stamp", stamp);
        				j.put("uid", intent.getStringExtra("uid"));
        				j.put("tid", intent.getStringExtra("tid"));
        				j.put("subcode", intent.getStringExtra("subcode"));
        				j.put("updatetime", intent.getLongExtra("updatetime",0));
        				j.put("terminaltype", intent.getStringExtra("terminaltype"));
        				j.put("remindmode", intent.getStringExtra("remindmode"));
        				j.put("opt", intent.getStringExtra("opt"));
        				j.put("dex", intent.getStringExtra("dex"));
        				j.put("remind", intent.getStringExtra("remind"));
        				j.put("remindmsg", intent.getStringExtra("remindmsg"));
        				JSONArray arr = new JSONArray(intent.getStringExtra("drugarr"));
        				j.put("drugarr", arr);

        				
        				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_DRUG_REMINDER,j.toString());
        				if(false == offerREQ(req)){
        					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
        					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
        					mApp.dispatchNetResponse(stamp,result,false);
        				}
        			} catch (JSONException e) {
        				// TODO Auto-generated catch block
        				e.printStackTrace();
        			}
        			
      		  }else if(COMMIT_GLYCOSE_SET.equalsIgnoreCase(subact)){

  				String stamp = intent.getStringExtra("stamp");
     			
      			try {
      				JSONObject j = new JSONObject();
      				j.put("stamp", stamp);
      				j.put("uid", intent.getStringExtra("uid"));
      				j.put("tid", intent.getStringExtra("tid"));      				      		        
      		        j.put("unit", intent.getStringExtra("unit"));
      		        j.put("voice", intent.getStringExtra("voice"));
      		        j.put("glycosylated", intent.getStringExtra("glycosylated"));
      		        j.put("beforelow", intent.getStringExtra("beforelow"));
      		        j.put("beforeupper", intent.getStringExtra("beforeupper"));
      		        j.put("afterlow", intent.getStringExtra("afterlow"));
      		        j.put("afterupper", intent.getStringExtra("afterupper"));
      		        j.put("bedtimelow", intent.getStringExtra("bedtimelow"));
      		        j.put("bedtimeupper", intent.getStringExtra("bedtimeupper"));
      		        j.put("dawnlow", intent.getStringExtra("dawnlow"));
      		        j.put("dawnupper", intent.getStringExtra("dawnupper"));
      				
      				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_COMMIT_GLYCOSE_SET,j.toString());
      				if(false == offerREQ(req)){
      					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
      					JSONObject sd = req.createSendData(false);
    					result.put("senddata", sd);
      					mApp.dispatchNetResponse(stamp,result,false);
      				}
      			} catch (JSONException e) {
      				// TODO Auto-generated catch block
      				e.printStackTrace();
      			}
      			
    		  }	    			
    		}else if(DOWNLOAD_ACTION.equalsIgnoreCase(action)){
    			String subact = intent.getStringExtra("sub_act");
    			if(DOWNLOAD_USER_FACE.equalsIgnoreCase(subact)){
	    			String uid = intent.getStringExtra("uid");
	    			String type = intent.getStringExtra("type");
	    			String stamp = intent.getStringExtra("stamp");
	    			String path = intent.getStringExtra("path");
	    			
	    			try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("type", type);
	    				j.put("uid", uid);
	    				
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_DOWNLOAD_USERFACE,j.toString());
	    				req.setFilePath(path);
	    				
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    			}else if(DOWNLOAD_DEVICE_FACE.equalsIgnoreCase(subact)){
    				String tid = intent.getStringExtra("tid");
	    			String type = intent.getStringExtra("type");
	    			String stamp = intent.getStringExtra("stamp");
	    			String path = intent.getStringExtra("path");
	    			
	    			try {
	    				JSONObject j = new JSONObject();
	    				j.put("stamp", stamp);
	    				j.put("type", type);
	    				j.put("tid", tid);
	    				
	    				HTTPREQ req = new HTTPREQ(HTTPREQ.CMD_DOWNLOAD_DEVFACE,j.toString());
	    				req.setFilePath(path);
	    				if(false == offerREQ(req)){
	    					JSONObject result = new JSONObject("{\"code\":\"10001\"}");
	    					JSONObject sd = req.createSendData(false);
        					result.put("senddata", sd);
	    					mApp.dispatchNetResponse(stamp,result,false);
	    				}
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    			}
    		}
    	}
        return START_STICKY;  
    }  
    
    @Override  
    public void onDestroy() {  
        logd("onDestroy"); 
        if(mThread != null){
        	try {
				offerREQ(new HTTPREQ("STOP", null));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	mThread.stopRunning();
        	mThread = null;
        }
        super.onDestroy();  
    } 
    
    private boolean offerREQ(HTTPREQ in){
    	if(false == mApp.checkNetwork())
    		return false;
    	if(mApp.isUserSignIn() == false){
    		if((in.isLogInCmd() == false) && (in.isAllowedCmdWithoutLogIn() == false)){
    			logd("offerREQ:not login for in= "+ in);
    			return false;
    		}
    	}
    	int size = mReqQueue.size();
    	while(size >= MAX_QUEUE_SIZE){
    		HTTPREQ dis = mReqQueue.poll();
    		logd("discard HTTPREQ:" + dis);
    		size = mReqQueue.size();
    	}
    	boolean ret = mReqQueue.offer(in);
    	logd("offerREQ:" + in + " ret="+ret);
    	
    	return ret;
    }
    
    class HttpsThread extends Thread{
    	private boolean stop = false;
    	
    	public void stopRunning(){
    		stop = true;
    	}
    	
    	@Override
    	public void run(){
    		int login_waiting_count = 20;
    		while(!stop){
    			try {
    				if(mApp.getStatus(HealthApp.STATUS_LOGIN_PROCESSING)){
    					logd("HttpsThread:login now waiting");
    					SystemClock.sleep(500);
    					login_waiting_count --;
    					if(login_waiting_count < 0){
    						logd("HttpsThread:login waiting timeout");
    					}else{
    						continue;
    					}
    				}
    				login_waiting_count = 20;
					HTTPREQ req = mReqQueue.take();
					logd("HttpsThread:get req="+req);
					if(req.mCmd.equals("STOP")){
						mReqQueue.clear();
						stop = true;
						continue;
					}
					
					if(HTTPREQ.CMD_SIGN_OUT.equals(req.mCmd)){
						logd("HttpsThread:get req= SIGN_OUT");
						mApp.signOut();
						while(mReqQueue.size() > 0){
							HTTPREQ dis = mReqQueue.peek();
							if(dis.mCmd.equals("STOP")){
								logd("HttpsThread:find STOP req when SIGN_OUT");
								mReqQueue.clear();
								stop = true;
								continue;
							}
							dis = mReqQueue.take();
							logd("HttpsThread:get discard ="+dis);
						}
						String stamp = null;
						try {
							stamp = req.getStamp();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mApp.dispatchNetResponse(stamp,null,false);
						continue;
					}
					
					if(req.isNeedSession()){
						if(mApp.checkLogInSession() == false){
							logd("HttpsThread:login timeout reget session code");
							if(false == req.isLogInCmd()){
								if(false == req.expired())
									offerREQ(req);
								req = buildALogInReq();
							}
						}
					}
					
					if(req.isHttpUploadReq()){
						HTTPUploadTask ht = new HTTPUploadTask();
						ht.execute(req);
					}else if(req.isHttpDownloadReq()){
						HTTPDownloadTask dt = new HTTPDownloadTask();
						dt.execute(req);
					}else{
						SSLReqTask rt = new SSLReqTask();
						rt.execute(req);
						if(req.isLogInCmd()){
							mApp.setStatus(HealthApp.STATUS_LOGIN_PROCESSING, true);
						}
					}
					logd("HttpsThread:do "+req);
					
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    		
    		logd("HttpsThread quit");
    	}
    }
    
    /*private HttpClient getClient() {  
        BasicHttpParams params = new BasicHttpParams();  
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);  
        HttpProtocolParams.setUseExpectContinue(params, false);  
      
        SchemeRegistry schReg = new SchemeRegistry();  
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), HttpConf.port));
      
        ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, schReg);  
        return new DefaultHttpClient(connMgr, params);  
    }  */
    
    private SSLContext mSSLContext = null;
    private MyX509TrustManager mtm = null;
    
    class SSLSocketFactoryEx extends SSLSocketFactory {
    	 
        public SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException,
                KeyManagementException, KeyStoreException, UnrecoverableKeyException {

            super(truststore);
        }


        @Override
        public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
                throws IOException, UnknownHostException {

            //injectHostname(socket, host);
            return mSSLContext.getSocketFactory().createSocket(socket, host, port, autoClose);
        }


        @Override
        public Socket createSocket() throws IOException {
            return mSSLContext.getSocketFactory().createSocket();
        }

        private void injectHostname(Socket socket, String host) {
            try {
                Field field = InetAddress.class.getDeclaredField("hostName");
                field.setAccessible(true);
                field.set(socket.getInetAddress(), host);
            } catch (Exception ignored) {

            }
        }
    }
    
    private void sslInit(){
    	if(mSSLContext != null)
    		return;
    	
    	mSSLContext = null;
		try {
			if(mtm == null){	
				mtm = new MyX509TrustManager(mApp);
			}
			TrustManager[] tms = new TrustManager[]{mtm};  			
	        // 初始化X509TrustManager中的SSLContext  
			mSSLContext = SSLContext.getInstance("TLS");
			mSSLContext.init(null, tms, new SecureRandom()); 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
    		
    }
    
	private HttpClient getSSLClient() {
		sslInit();
		
		if(mSSLContext == null)
			return new DefaultHttpClient();
		
		try{  
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			trustStore.load(null, null);
			SSLSocketFactory ssf = new SSLSocketFactoryEx(trustStore);
			
			ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		 
			BasicHttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
			HttpProtocolParams.setUseExpectContinue(params, false);  
			HttpConnectionParams.setConnectionTimeout(params, 10*1000);
			HttpConnectionParams.setSoTimeout(params, 10*1000);
			
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), HttpConf.port));
			registry.register(new Scheme("https", ssf, HttpConf.sslport));
		 
			ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
		 
			return new DefaultHttpClient(ccm, params);
		}catch (Exception e) {
			return new DefaultHttpClient();
		}
	}
	
	private class HTTPDownloadTask extends AsyncTask<HTTPREQ,Void,JSONObject>{
		private HTTPREQ mReq;
		
		private void dealResult(JSONObject result, boolean canceled){  		
    		String state = null;
    		if(result != null){
				try {
					if(result.has("state"))
						state = result.getString("state");
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					state = null;
				}
    		}
			logd("dealResult: try state = " + state);
    		try {
    			//int code = result.getInt("code");
    			if((state != null) && state.equals("03") && mReq.isNeedSession()){
    				logd("dealResult:session failed;resend "+mReq);
    				mApp.clearLogInSession();
    				if(false == mReq.expired())
    					offerREQ(mReq);
    			}else{
    				String stamp = mReq.getStamp();
    				mApp.dispatchNetResponse(stamp,result,canceled);
    			}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		
    	}
    	
    	@Override
		protected void onCancelled(JSONObject result){
			dealResult(result, true);
		}
    	
		@Override
		protected void onPostExecute(JSONObject result){
			dealResult(result, false);
		}
		
		@Override
		protected JSONObject doInBackground(HTTPREQ... arg) {
			mReq = arg[0];
			
        	try {
        		String uri = mReq.getUri();
        		String filepath = mReq.getFilePath();
        		if((filepath == null) || (filepath.trim().length() == 0)){
        			if(NET_DEBUG){
        				Log.d("NET_DEBUG","return to:"+uri + " code = 10002");
        			}
    				JSONObject jr = new JSONObject();
    	        	JSONObject sd = mReq.createSendData(false);
    				jr.put("senddata", sd);
    	        	jr.put("code", 10002);
    	        	return jr;	
        		}
        		
        		File f = new File(filepath);
        		if(f.exists())
        			f.delete();
        		
        		netLogd("do req:"+uri);
            	
            	HttpGet get = new HttpGet(uri);
            	
            	HttpParams httpParameters = new BasicHttpParams();
		        HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);
		        HttpConnectionParams.setSoTimeout(httpParameters, 10 * 1000);
		        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
		        
	            HttpResponse response = httpClient.execute(get);
	            
	            int code = response.getStatusLine().getStatusCode();
	            netLogd("return to:"+uri + " code = "+ code);
	    
	            if (code == 200){  
	            	Header[] header = response.getHeaders("Content-Disposition");
	            	String value = null;
	            	if((header != null) && (header.length > 0) && (header[0] != null)){
	            		value = header[0].getValue();
	            	}
	            	netLogd("download return data:"+value);
	            	
	            	if((value == null) || (value.trim().length() == 0)){
	            		JSONObject jr = new JSONObject();
		    			jr.put("code", code);
		    			jr.put("state", "FF");
		    			JSONObject sd = mReq.createSendData(false);
		    			jr.put("senddata", sd);
		    			jr.put("downloadfile", filepath);
		    			return jr;
	            	}
	            	
	            	JSONObject jr = new JSONObject(value);
	            	String state = jr.getString("state");
	            	if(state.equals("00")){
		            	InputStream is = response.getEntity().getContent();
		            	FileOutputStream fos = new FileOutputStream(f);
		            	byte[] bytes = new byte[1024]; 
		            	int len = 0;
		            	while((len = is.read(bytes)) != -1){
		            		fos.write(bytes,0,len);
		            	}
		            	fos.flush();
		            	fos.close();
		            	is.close();
	            	}
	            	
	    			jr.put("code", 200);
	    			JSONObject sd = mReq.createSendData(false);
	    			jr.put("senddata", sd);
	    			jr.put("downloadfile", filepath);
	    			return jr;
	            }else{
	            	JSONObject jr = new JSONObject();
	    			jr.put("code", code);
	    			JSONObject sd = mReq.createSendData(false);
	    			jr.put("senddata", sd);
	    			jr.put("downloadfile", filepath);
	    			return jr;
	            }
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}    
        	
        	netLogE("return to "+ mReq.getUri() + " code = 10003");
        	
        	try{
    			JSONObject jr = new JSONObject();
            	JSONObject sd = mReq.createSendData(false);
    			jr.put("senddata", sd);
            	jr.put("code", 10003);
            	return jr;
			}catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		
	}
	
	private class HTTPUploadTask extends AsyncTask<HTTPREQ,Void,JSONObject>{
		private HTTPREQ mReq;
		
		private void dealResult(JSONObject result, boolean canceled){  		
    		String state = null;
    		if(result != null){
				try {
					if(result.has("state"))
						state = result.getString("state");
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					state = null;
				}
    		}
			logd("dealResult: try state = " + state);
    		try {
    			//int code = result.getInt("code");
    			if((state != null) && state.equals("03") && mReq.isNeedSession()){
    				logd("dealResult:session failed;resend "+mReq);
    				mApp.clearLogInSession();
    				if(false == mReq.expired())
    					offerREQ(mReq);
    			}else{
    				String stamp = mReq.getStamp();
    				mApp.dispatchNetResponse(stamp,result,canceled);
    			}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		
    	}
    	
    	@Override
		protected void onCancelled(JSONObject result){
			dealResult(result, true);
		}
    	
		@Override
		protected void onPostExecute(JSONObject result){
			dealResult(result, false);
		}
		
		@Override
		protected JSONObject doInBackground(HTTPREQ... arg) {
			mReq = arg[0];
			
			try{
				String path = mReq.getFilePath();
				String uri = mReq.getUri();
				if((path == null) || (path.trim().length() == 0)){
					netLogE("return to:"+uri + " code = 10002");
					
					JSONObject jr = new JSONObject();
		        	JSONObject sd = mReq.createSendData(false);
					jr.put("senddata", sd);
		        	jr.put("code", 10002);
					return null;
				}
				
				File f = new File(path);
				if(!f.exists()){
					JSONObject jr = new JSONObject();
	            	JSONObject sd = mReq.createSendData(false);
	    			jr.put("senddata", sd);
	            	jr.put("code", 10002); //file not exist
	    			return jr;
				}
				
	        	JSONObject je = mReq.createJSONEntity();
				if(mReq.isNeedSession()){
					je.put("sessioncode", mApp.getSession());
				}
				
				netLogd("send to:"+uri);
				netLogd("send data:"+je.toString());
				
				MultipartEntity entity = new MultipartEntity();
				entity.addJsonPart("jsonvalue", je.toString());
				entity.addFilePart("images", f); 
				entity.addEnd();
				
				HttpPost post = new HttpPost(uri);
				post.setEntity(entity);
				Header cth = entity.getContentType();
				post.setHeader(cth);
				post.setHeader("Content-Disposition", je.toString());

		        HttpParams httpParameters = new BasicHttpParams();
		        HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);
		        HttpConnectionParams.setSoTimeout(httpParameters, 10 * 1000);
		        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
				
				HttpResponse response = httpClient.execute(post);
	            
	            int code = response.getStatusLine().getStatusCode();
	            
	            netLogd("return to:"+uri + " code = "+ code);
	            
	            entity.close();
	            
	            if (code == 200){  
	            	HttpEntity replyEntity = response.getEntity();  
	            	long len = replyEntity.getContentLength();
	            	boolean chunked = replyEntity.isChunked();
	            	if((len <= 0) && (false == chunked)){
	            		return null;
	            	}
	    			String responseString = EntityUtils.toString(replyEntity,"UTF-8").trim(); 
	    			netLogd("return data:"+responseString);
	    			
	    			JSONObject jr = new JSONObject(responseString);
	    			jr.put("code", 200);
	    			JSONObject sd = mReq.createSendData(false);
	    			jr.put("senddata", sd);
	    			jr.put("uploadfile", path);
	    			return jr;
	            }else{
	            	JSONObject jr = new JSONObject();
	            	JSONObject sd = mReq.createSendData(false);
	    			jr.put("senddata", sd);
	            	jr.put("code", code);
	    			return jr;
	            }
			} catch (JSONException e) {
				
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			netLogE("return to "+ mReq.getUri() + " code = 10003");
			
			try{
			JSONObject jr = new JSONObject();
        	JSONObject sd = mReq.createSendData(false);
			jr.put("senddata", sd);
        	jr.put("code", 10003);
        	return jr;
			}catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
    
    private class SSLReqTask extends AsyncTask<HTTPREQ,Void,JSONObject>{
    	private HTTPREQ mReq;
    	
    	private void dealResult(JSONObject result, boolean canceled){
    		
    		String state = null;
    		if(result != null){
				try {
					if(result.has("state"))
						state = result.getString("state");
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					state = null;
				}
    		}
			logd("dealResult: try state = " + state);
    		try {
    			//int code = result.getInt("code");
    			if((state != null) && state.equals("03") && mReq.isNeedSession()){
    				logd("dealResult:session failed;resend "+mReq);
    				mApp.clearLogInSession();
    				if(false == mReq.expired())
    					offerREQ(mReq);
    			}else{
    				String stamp = mReq.getStamp();
    				mApp.dispatchNetResponse(stamp,result,canceled);
    			}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		
    	}
    	
    	@Override
		protected void onCancelled(JSONObject result){
			dealResult(result, true);
		}
    	
		@Override
		protected void onPostExecute(JSONObject result){
			dealResult(result, false);
		}
		
		@Override
		protected JSONObject doInBackground(HTTPREQ... arg) {
			mReq = arg[0];
			
            try {
            	String uri = mReq.getUri();
            	logd("do req:"+uri);
    			HttpPost post = new HttpPost(uri);   
    			JSONObject je = mReq.createJSONEntity();
    			if(mReq.isNeedSession()){
    				je.put("sessioncode", mApp.getSession());
    			}
    			    			
    			netLogd("send to:"+uri);
    			netLogd("send data:"+je.toString());

				post.setEntity(new StringEntity(je.toString(), "UTF-8"));
				post.setHeader(HttpConf.HEADER_CONNECTION, "close");
				post.addHeader(HttpConf.HEADER_CONTENT_TYPE, HttpConf.HEADER_CONTENT_TYPE_JSON);
	            
	            //HttpClient httpClient = getClient(); 
				HttpClient httpClient = getSSLClient();
	            HttpResponse response = httpClient.execute(post);
	            
	            int code = response.getStatusLine().getStatusCode();
	            
	            netLogd("return to:"+uri + " code = "+ code);
	            
	            if (code == 200){  
	            	HttpEntity replyEntity = response.getEntity();  
	            	long len = replyEntity.getContentLength();
	            	boolean chunked = replyEntity.isChunked();
	            	if((len <= 0) && (false == chunked)){
	            		return null;
	            	}
	    			String responseString = EntityUtils.toString(replyEntity,"UTF-8").trim();  
	    			netLogd("return data:"+responseString);
	    			
	    			JSONObject jr = new JSONObject(responseString);
	    			jr.put("code", 200);
	    			JSONObject sd = mReq.createSendData(false);
	    			jr.put("senddata", sd);
	    			return jr;
	            }else{
	            	JSONObject jr = new JSONObject();
	            	JSONObject sd = mReq.createSendData(false);
	    			jr.put("senddata", sd);
	            	jr.put("code", code);
	    			return jr;
	            }
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            
            netLogE("return to "+ mReq.getUri() + " code = 10003");
			
            try{
    			JSONObject jr = new JSONObject();
            	JSONObject sd = mReq.createSendData(false);
    			jr.put("senddata", sd);
            	jr.put("code", 10003);
            	return jr;
			}catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
    	
    }
}
